package db

import (
	"fmt"
	"github.com/go-redis/redis"
	"log"
	"shop-common/library/config"
	"shop-common/library/env"
	"time"
)

func NewRedis(redisSetting *config.Redis) (*redis.Client, error) {
	if redisSetting == nil {
		return nil, fmt.Errorf("RedisSetting is nil")
	}
	if redisSetting.Addr == "" {
		return nil, fmt.Errorf("Lack of redisSetting.Addr")
	}

	if !env.IsDevMode() {
		if redisSetting.Password == "" {
			return nil, fmt.Errorf("Lack of redisSetting.Password")
		}
	}

	idleTimeout := 240
	if redisSetting.IdleTimeout > 0 {
		idleTimeout = redisSetting.IdleTimeout
	}

	option := &redis.Options{
		Addr: redisSetting.Addr,
		//Password:     "123456",
		DB:           redisSetting.DB,
		MinIdleConns: redisSetting.MaxIdle,
		MaxConnAge:   time.Duration(redisSetting.MaxActive),
		IdleTimeout:  time.Duration(idleTimeout) * time.Second,
	}
	if redisSetting.Password != "" {
		option.Password = redisSetting.Password
	}

	client := redis.NewClient(option)
	pool, err := client.Ping().Result()
	if err != nil {
		return nil, err
	}
	log.Printf("cache pong reslut %s\n", pool)
	return client, nil
}
